package com.ykt.service;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.ykt.common.utils.ObjectUtil;
import com.ykt.common.utils.page.PageData;
import com.ykt.common.utils.page.PageParam;
import com.ykt.model.Address;
import com.ykt.model.UserAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 地址服务
 */
public class UserAddressService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserAddressService.class);

    private Address addressDao = Address.dao;
    private UserAddress userAddressDao = UserAddress.dao;

    /**
     * 根据USERID查询所有地址
     *
     * @param param userId 和 分页参数
     * @return 地址信息
     */
    public PageData<UserAddress> paginateByUserId(PageParam<Integer> param) {
        PageData<UserAddress> pd = userAddressDao.paginateByUserId(param);

        if(pd != null && pd.getPageData() != null && !pd.getPageData().isEmpty()){
            setName(pd.getPageData());
        }

        return pd; // 使用引用，无需重新设值
    }

    @Before(Tx.class)
    public void setDefaults(Integer id, Integer userId) {
        List<UserAddress> defaults = userAddressDao.findDefaults(userId);
        if(defaults != null && !defaults.isEmpty()){

            for (UserAddress ua : defaults) {
                ua.set("defaults", 0);
                ua.update();
            }
        }

        UserAddress ua = userAddressDao.findById(id);
        ua.set("defaults", 1);
        ua.update();
    }

    public UserAddress findDefaults(Integer userId) {
        List<UserAddress> defaults = userAddressDao.findDefaults(userId);
        if(defaults == null || defaults.isEmpty()){
            return null;
        }

        defaults = this.setName(defaults.subList(0, 1));// 截取第一个

        return defaults.get(0); // 获取第一个
    }

    private List<UserAddress> setName(List<UserAddress> userAddresses){
        List<Integer> ids = new ArrayList<>();
        for (UserAddress userAddress : userAddresses) {

            Integer provinceId = userAddress.getInt("provinceId");
            Integer cityId = userAddress.getInt("cityId");
            Integer districtId = userAddress.getInt("districtId");
            if(provinceId == null || cityId == null || districtId == null){
                continue;
            }

            if(!ids.contains(provinceId)){
                ids.add(provinceId);
            }
            if(!ids.contains(cityId)){
                ids.add(cityId);
            }
            if(!ids.contains(districtId)){
                ids.add(districtId);
            }
        }

        List<Address> addresses = addressDao.findByIds(ids);
        if(addresses == null || addresses.isEmpty()){
            return userAddresses;
        }

        Map<Integer, Address> addressMap = new HashMap<>();
        for (Address address : addresses) {
            addressMap.put(address.getInt("id"), address);
        }

        for (UserAddress userAddress : userAddresses) {
            Integer provinceId = userAddress.getInt("provinceId");
            Integer cityId = userAddress.getInt("cityId");
            Integer districtId = userAddress.getInt("districtId");
            if(provinceId == null || cityId == null || districtId == null){
                continue;
            }

            String provinceName = ObjectUtil.get(addressMap.get(provinceId), addressMap.get(provinceId).get("name"));
            userAddress.put("provinceName", provinceName);

            String cityName = ObjectUtil.get(addressMap.get(cityId), addressMap.get(cityId).get("name"));
            userAddress.put("cityName", cityName);

            String districtName = ObjectUtil.get(addressMap.get(districtId), addressMap.get(districtId).get("name"));
            userAddress.put("districtName", districtName);
        }

        return userAddresses; // 使用引用，无需重新设值
    }

    public UserAddress find(Integer id) {
        return userAddressDao.findById(id);
    }

    @Before(Tx.class)
    public void delete(Integer id) {
        userAddressDao.deleteById(id);
    }

    @Before(Tx.class)
    public int save(UserAddress userAddress) {
        boolean flag = false;

        // 查询如更新用户
        Integer id = userAddress.get("id");
        if (id == null || id < 0) {
            flag = insert(userAddress);
            if (!flag) {
                LOGGER.warn("Save UserAddress error, userId: {}", userAddress.get("user_id"));
                return -1;
            }
        } else {
            flag = update(userAddress);
            if (!flag) {
                LOGGER.warn("Update UserAddress error, userId: {}", userAddress.get("user_id"));
                return -1;
            }
        }

        // 返回ID
        return userAddress.get("id");
    }

    private boolean insert(UserAddress userAddress) {
        return userAddress.save();//直接保存即可
    }

    private boolean update(UserAddress userAddress) {
        return userAddress.update();
    }
}
